<template>
	<view>
		<view class="searchBar">
			<uni-search-bar v-model="searchValue" :radius="15" @focus="backToSearch" @input="changeGlobalData"
				@confirm="searchMusic" cancelButton="none" clearButton="auto"></uni-search-bar>
		</view>
		<view class="searchList">
			<view v-for="item in musicList" :key="item.id">
				<uni-list-item showArrow :title="item.name" @click="enterPlayer(item.id)" link="switchTab"
					:note="connectName(item.artists)">
					<view slot="footer" v-show="item.mvid!=0">
						<image class="mvIcons" src="/static/imgs/MV.png"></image>
					</view>
				</uni-list-item>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				searchValue: "",
				musicList: [],
				arNames: ""
			}
		},
		onLoad() {
			this.searchValue = getApp().globalData.searchValue
			this.searchMusic()
		},
		onBackPress(option) {
			uni.switchTab({
				url: "./index"
			})
			return true
		},
		methods: {
			saveKeyword(keyword) {
				if(keyword==""){
					return
				}
				uni.getStorage({
					key: 'OldKeys',
					success: (res) => {
						var OldKeys = JSON.parse(res.data);
						var findIndex = OldKeys.indexOf(keyword);
						if (findIndex == -1) {
							OldKeys.unshift(keyword);
						} else {
							OldKeys.splice(findIndex, 1);
							OldKeys.unshift(keyword);
						}
						//最多10个纪录
						OldKeys.length > 10 && OldKeys.pop();
						uni.setStorage({
							key: 'OldKeys',
							data: JSON.stringify(OldKeys)
						});
					},
					fail: (e) => {
						var OldKeys = [keyword];
						uni.setStorage({
							key: 'OldKeys',
							data: JSON.stringify(OldKeys)
						});
					}
				});
			},
			searchMusic() {
				uni.showToast({
					title: "搜索：" + getApp().globalData.searchValue
				})
				this.saveKeyword(getApp().globalData.searchValue);
				uni.request({
					url: "https://autumnfish.cn/search?keywords=" + getApp().globalData.searchValue,
					success: res => {
						this.musicList = res.data.result.songs
						// console.log(this.musicList)
					}
				})
			},
			changeGlobalData() {
				getApp().globalData.searchValue = this.searchValue
			},
			backToSearch() {
				uni.navigateTo({
					url: "./search"
				})
			},
			enterPlayer(id) {
				// console.log(id)
				uni.navigateTo({
					url: "../play/play?id=" + id
				})
			},
			connectName(data) {
				let names = data.map(item => {
					return item.name
				})
				let res = ""
				for (let i = 0; i < names.length; i++) {
					if (i == names.length - 1) {
						res = res + names[i]
					} else {
						res = res + names[i] + "/"
					}
				}
				return res
			}
		}
	}
</script>
<style lang="scss">
	.mvIcons {
		margin-top: 5px;
		width: 30px;
		height: 30px;
	}

	.searchBar {
		position: sticky;
		top: var(--window-top);
		z-index: 99;
		flex-direction: row;
		margin: 0px;
		background-color: #ffffff;
	}
</style>
